﻿<?php
session_start();
require_once("../Structure/fonctions.php");

$PAGE_TITLE = "Article - Lolgames";
$CONTENT_INCLUDE = "article.html";

if (isset($_GET["id"])) {
    $bdd = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_BASE);
	
	include("../Structure/updateUser.php");
	
	$userID = "";
	
	if(isset ($_SESSION["user_id"]))
	{
		if(isset($_POST["publish"]))
		{
			if($_POST["publish"] == "accept")
			{
				$query = "UPDATE	articles
						  SET 		statusID = 1
						  WHERE		id = ".$_GET['id']." ;";
				
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
				
				$query = "SELECT	autorID
						  FROM 		articles
						  WHERE 	id = ".$_GET['id']." ;";
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
				
				$row_temp = mysqli_fetch_array($res);
				
				$autorID = $row_temp['autorID'];
				
				if($user["roleID"] == 0)
				{
					$query = "UPDATE	users
						  SET		roleID = 1
						  WHERE 	id = ".$autorID." ;";
				
					$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
				}
			}
			else
			{
				$query = "UPDATE	articles
						  SET		statusID = 3
						  WHERE		id = ".$_GET['id']." ;";
				
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
			}
		}
	
		if(isset($_POST['editCom']))
		{
			if($_POST['wrCom'] != NULL)
			{
				$_POST['wrCom'] = addslashes($_POST['wrCom']);

				$query = "UPDATE	comments
						  SET		content = '".$_POST['wrCom']."'
						  WHERE		id = ".$_POST['id']." ;";
				
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
			}
		}
		if(isset($_POST['subCom']))
		{
			if($_POST['wrCom'] != NULL)
			{
				$_POST['wrCom'] = addslashes($_POST['wrCom']);

				$query = "INSERT INTO comments (autorID, articleID, content, statusID, note, date)
						  VALUES (".$_SESSION['user_id'].", ".$_GET['id'].", '".$_POST['wrCom']."', 1, 0, SYSDATE() ) ;";
				
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
			}
		}

		if(isset($_POST['deleteCom'])) {
			$query = "UPDATE	comments
					  SET		statusID = 3
					  WHERE		id = ".$_POST['id']." ;";

			$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
		}
	
		//
		//			Edition d'un article
		//
		
		if(isset($_POST['edit']))
		{
			$isComsAlwd = 0;
			$statusID = 0;
			
			if(isset($_POST['comment_allowed'])) {
				if($_POST['comment_allowed'] == 'True'){$isComsAlwd = 1;}
			}
			
			if($user['roleID'] == 3){$statusID = 1;}
			
			$query = "UPDATE	articles
					  SET		content = '".$_POST['content']."', commentAllowed = ".$isComsAlwd.", statusID = ".$statusID."
					  WHERE   	id = ".$_GET['id'].";";
			
			$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
			
			$result = "";
			///Analyse le contenu de l'article et stocke les liens de toutes les images (REGEX)
			preg_match_all('#<img .*src=(?:"|\')(.+)(?:"|\').*>#Uis', $_POST['content'], $result);
			
			///Insère les images en base
			$i = 0;
			foreach($result as $value)
			{
				if($i != 0)
				{
					foreach($value as $link)
					{
						$query = "INSERT INTO	images(autorID, link, statusID)
								  VALUES		('".$autorID."', '".$link."', 1)";
						$res = mysqli_query($bdd, $query) or die (mysqli_error($bdd));
					}
				}
				$i++;
			}
			
			if ($_FILES["articleImg"]["error"] == 0)
			{
				if ($_FILES["articleImg"]["size"] < 5242880)///Taille inférieur a 5Mio
				{
					$extensions_autorisees = array( '.jpg' , '.jpeg' , '.gif' , '.png' , '.bmp' );
					$extension_upload = strtolower(strrchr($_FILES["articleImg"]["name"], '.'));
					if (in_array($extension_upload, $extensions_autorisees))//On vérifie l'extension
					{
						//déplace le fichier uploadé
						$move = move_uploaded_file($_FILES["articleImg"]["tmp_name"], LOCALROOT."img/article/".$_GET['id'].$extension_upload);
						//On l'insere en base puis on met à jour l'article avec l'id de l'image
						if($move)
						{
							$query ="SELECT	imageID
									 FROM	articles
									 WHERE	id = ".$_GET['id'].";";
									
							$res = mysqli_query($bdd, $query);
							
							$row = mysqli_fetch_array($res);
							
							$link = "img/article/".$_GET['id'].$extension_upload;
							
							$imgId = $row['imageID']; 
							if($imgId == 0)
							{
								$query = "INSERT INTO images (link, autorID, statusID)
									 	  VALUES      ('img/article/".$_GET['id'].$extension_upload."', '".$_SESSION["user_id"]."', 1) ;";
								$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

								$query = "UPDATE  articles
										  SET     imageID = LAST_INSERT_ID()
										  WHERE   id = ".$_GET['id']." ;";
								$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
							}
							else
							{
								$query = "UPDATE  images
										  SET     link = '".$link."', statusID = 1
										  WHERE   id = ".$imgId." ;";
										  
								$res = mysqli_query($bdd, $query);
							}
						}
					}
				}
			}
		}
		
        //
		//			Ajout d'une note sur un commentaire ou un article 
		//
		
        if(isset($_POST["note"])) 
		{
            if(isset($_POST["comType"])) 
			{
                $isCom = 1;
                $id = $_POST["comID"];
                $table = "comments";
            } 
			else 
			{
                $isCom = 0;
                $id = $_GET["id"];
                $table = "articles";
            }

            $query = "SELECT  id
					  FROM 	  notes
					  WHERE   autorID = ".$_SESSION["user_id"]."
					  	AND   originID = ".$id."
					  	AND   isComment = ".$isCom.";";
            $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

            if(mysqli_num_rows($res) == 1) {
                $note = mysqli_fetch_array($res);
                $query = "UPDATE  notes
                          SET     note = ".$_POST["note"].", date = SYSDATE()
                          WHERE   id = ".$note['id']." ;";
                $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
            }
            else {
                $query = "INSERT INTO notes (autorID, originID, isComment, note, date)
						  VALUES      (".$_SESSION['user_id'].", ".$id.", ".$isCom.", ".$_POST["note"].", SYSDATE()) ;";
                $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
            }

            $query = "UPDATE  ".$table."
					  SET     note = (SELECT  SUM(note) FROM notes
									  WHERE   originID = ".$id."
                                      AND     isComment = ".$isCom.")
                      WHERE   id = ".$id." ;";

            $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
        }
		$userID = $_SESSION['user_id'];
	}
	
	//
	//			Récupération de l'article en base
	//
	
    $query = "SELECT  			a.autorID, u.pseudo autor, title, content, type, a.statusID, a.note note, n.note pouce, commentAllowed, link, a.date, i.statusID imgStatus
              FROM    			articles a
              JOIN    			users u ON a.autorID = u.id
              JOIN    			images i ON a.imageID = i.id
              LEFT OUTER JOIN   notes n ON n.originID = a.id
				AND    			isComment = 0
				AND    			n.autorID = '".$userID."'
              WHERE   			a.id = ".$_GET['id']." ;";
    $res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

    if(mysqli_num_rows($res) == 1) {
        $row = mysqli_fetch_array($res);
        $PAGE_TITLE = $row["title"]." - Lolgames";

        if (isset($_SESSION["user_id"])) {
            if ($row['autorID'] == $_SESSION['user_id']) {
                $myArticle = true;
            }
            else {
                $myArticle = false;
            }
        }
        else {
            $myArticle = false;
        }
    }
	
	if(isset($row))
	{
		//
		//			Gestion de l'historique
		//
		
		if(isset($_SESSION["user_id"]))
		{
			$query = "SELECT  id
                      FROM 	  historics
                      WHERE   viewerID = ".$_SESSION["user_id"]."
                      	AND   articleID = ".$_GET["id"]." ;";
			$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));

			if(mysqli_num_rows($res) == 1) {
				$hist = mysqli_fetch_array($res);
				$query = "UPDATE  historics
						  SET     date = SYSDATE()
						  WHERE   id = ".$hist['id']." ;";
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
			}
			else {
				$query = "INSERT INTO historics (viewerID, articleID, date)
						  VALUES      (".$_SESSION['user_id'].", ".$_GET['id'].", SYSDATE()) ;";
				$res = mysqli_query($bdd, $query) or die(mysqli_error($bdd));
			}
		}
		
		//
		//			Gestion des commentaires
		//
		
		if($row['commentAllowed'])
		{
			$query = "SELECT  			c.*, u.pseudo autor, n.note pouce, link, i.statusID imgStatus
                      FROM    			comments c
                      JOIN    			users u ON c.autorID = u.id
                      JOIN    			images i ON u.avatarID = i.id
                      LEFT OUTER JOIN   notes n ON n.originID = c.id
						AND    			isComment = 1
                        AND    			n.autorID = '".$userID."'
                      WHERE     		articleID = '".$_GET['id']."'
                      	AND				c.statusID = 1
                      ORDER BY  		c.date DESC;";
			$res_comms = mysqli_query($bdd, $query) or die(mysqli_error($bdd));	
		}
	}
}

include_once("../Structure/structure.php");

?>